﻿<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图片跟随鼠标</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        width: 100%;
      }
      #container {
        margin: 30px auto;
        width: 100%;
        height: 700px;
        display: block;
        position: relative;
        border-radius: 10px;
      }
      #container::after {
        content: "";
        background: url(img/bg1.jpg) no-repeat center center;
        opacity: 0.2;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        position: absolute;
        z-index: -1;
        background-size: 100%;
        border-radius: 10px;
      }
      #container img {
        width: 5%;
        position: absolute;
        top: 10px;
        left: 10px;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <img src="img/butterfly1.png" />
    </div>
    <script>
      //给整个文档对象绑定一个鼠标移动的事件
      document.addEventListener('mousemove',function(e){
        var ev = e || window.event;
        var x = ev.pageX;
        var y = ev.pageY;
        var img = document.querySelector('img');
        img.style.left = x + 'px';
        img.style.top = y + 'px';
      });
    </script>
  </body>
</html>
